﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using Data.Common;
using Data.Condition;
using Data.Enum;
using Data.Model;
using Data.ViewModel;

namespace DataAccess.BikeManage
{
    /// <summary>
    ///     停车柱管理
    /// </summary>
    public class LockPile : DbBase, ILockPile
    {
        /// <summary>
        ///     根据id获取停车柱信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultInfo<jsh_lockpile> GetLockPile(int id)
        {
            var result = new ResultInfo<jsh_lockpile> {ResultNumber = ResultEnum.Error};
            try
            {
                var b = new jsh_lockpile();
                if (id > 0)
                {
                    string sql = string.Format("select * from jsh_lockpile where id={0}", id);
                    DataSet ds = ExcuteSqlDataSet(sql);
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        result.ResultNumber = ResultEnum.Success;
                        b = new jsh_lockpile(ds.Tables[0].Rows[0]);
                    }
                    else
                    {
                        result.ResultNumber = ResultEnum.Error;
                        result.Describe = "不存在该锁柱";
                    }
                    result.Obj = b;
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Describe = "查询锁柱失败";
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }

            return result;
        }

        /// <summary>
        ///     获取停车柱列表
        /// </summary>
        /// <param name="searchLockPileCondition"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ResultInfo<PagingDataSet<LockPileView>> GetLockPiles(SearchLockPileCondition searchLockPileCondition, int pageIndex, int pageSize)
        {
            var result = new ResultInfo<PagingDataSet<LockPileView>>();
            try
            {
                using (SqlCommand myCommand = GetProCommand())
                {
                    myCommand.CommandText = "Common_GetPagingRecords";
                    var fromClause = new StringBuilder();
                    fromClause.Append("jsh_lockpile with (nolock) ");
                    var whereClause = new StringBuilder();
                    if (!string.IsNullOrEmpty(searchLockPileCondition.LockPileNo))
                    {
                        whereClause.Append(string.Format(" and pileno='{0}' ", searchLockPileCondition.LockPileNo));
                    }
                    if (!string.IsNullOrEmpty(searchLockPileCondition.LockAddressName))
                    {
                        whereClause.Append(string.Format(" and areaid in (select id from jsh_area where area='{0}') ",
                            searchLockPileCondition.LockAddressName));
                    }
                    if (searchLockPileCondition.LockAreaId < 0)
                    {
                    }
                    if (searchLockPileCondition.LockAreaId >= 0)
                    {
                        whereClause.Append(
                            string.Format(" and areaid in (select ld.id from jsh_area ld where ld.id ={0}) ", searchLockPileCondition.LockAreaId));
                    }
                    if (searchLockPileCondition.Status < 0)
                    {
                    }
                    if (searchLockPileCondition.Status >= 0)
                    {
                        whereClause.Append(string.Format(" and status='{0}' ", searchLockPileCondition.Status));
                    }
                    if (!string.IsNullOrEmpty(searchLockPileCondition.ControlBoxNo))
                    {
                        whereClause.Append(string.Format(""));
                    }
                    if (whereClause.Length > 3)
                    {
                        whereClause.Remove(0, 5);
                    }

                    myCommand.Parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex - 1;
                    myCommand.Parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize;
                    myCommand.Parameters.Add("@FromClause", SqlDbType.VarChar, 1024).Value = fromClause.ToString();
                    myCommand.Parameters.Add("@SelectFields", SqlDbType.VarChar, 512).Value = "*";
                    myCommand.Parameters.Add("@WhereClause", SqlDbType.NVarChar, 4000).Value = whereClause.ToString();
                    myCommand.Parameters.Add("@SortField", SqlDbType.VarChar, 256).Value = "id";
                    myCommand.Parameters.Add("@SortFieldIsDesc", SqlDbType.Bit).Value = true;
                    myCommand.Parameters.Add("@ReturnRecordCount", SqlDbType.Bit).Value = true;
                    myCommand.Parameters.Add("@MaxRecords", SqlDbType.Int).Value = int.MaxValue;
                    myCommand.Parameters.Add("@TotalRecords", SqlDbType.Int).Direction = ParameterDirection.Output;
                    myCommand.Parameters.Add("@ReverseOrder", SqlDbType.Bit).Direction = ParameterDirection.Output;

                    var dataSet = new DataSet();
                    var da = new SqlDataAdapter(myCommand);
                    da.Fill(dataSet);

                    List<jsh_lockpile> list =
                        dataSet.Tables[0].Rows.Cast<DataRow>()
                            .Select(dataRow => new jsh_lockpile(dataRow))
                            .Where(temp => temp.TranByConstructFlag)
                            .ToList();

                    int totalRecords = Convert.ToInt32(myCommand.Parameters["@TotalRecords"].Value);
                    bool reverseOrder = Convert.ToBoolean(myCommand.Parameters["@ReverseOrder"].Value);

                    if (reverseOrder)
                        list.Reverse();
                    List<LockPileView> listView = PopulateLockPiles(list);

                    result.ResultNumber = ResultEnum.Success;
                    result.Obj = new PagingDataSet<LockPileView>
                    {
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        Records = listView,
                        TotalRecords = totalRecords
                    };
                }
            }
            catch (SqlException)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = "数据库错误，请联系管理员！";
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }

        /// <summary>
        ///     创建或者是更新停车柱的信息，有id就是更新没有id就是创建新的
        /// </summary>
        /// <param name="pile">停车柱信息</param>
        /// <returns></returns>
        public ResultInfo<int> CreateOrUpdateLockPile(jsh_lockpile pile)
        {
            var result = new ResultInfo<int>();
            try
            {
                string sql = string.Empty;
                if (pile != null)
                {
                    if (pile.id > 0)
                    {
                        sql =
                            string.Format(
                                "UPDATE jsh_LockPile SET [PSAMNO]={0},[PileNO]={1},[IP]={2},[CONTROLBOXID]={3},[CONTROLBOX]={4},[AreaID]={5},[Area]={6},[Status]={7}",
                                pile.Psamno, pile.Pileno, pile.Ip, pile.Controlboxid, pile.Controlbox, pile.Areaid,
                                pile.Area, pile.Status);
                    }
                    else
                    {
                        string check = string.Format("select id from jsh_lockpile where PileNO='{0}'", pile.Pileno);
                        DataSet dt = ExcuteSqlDataSet(check);
                        if (dt != null && dt.Tables[0].Rows.Count > 0)
                        {
                            result.ResultNumber = ResultEnum.Error;
                            result.Describe = "已经存在同名停车区域，请重新输入";
                        }
                        else
                        {
                            sql =
                                string.Format(
                                    "insert into jsh_lockpile([PSAMNO],[PileNO],[IP],[CONTROLBOXID],[CONTROLBOX],[AreaID],[Area],[Status]) " +
                                    "values('{0}','{1}','{2}',{3},'{4}',{5},'{6}','{7}') select @@identity id",
                                    pile.Psamno, pile.Pileno, pile.Ip, pile.Controlboxid, pile.Controlbox, pile.Areaid,
                                    pile.Area, pile.Status);
                        }
                    }
                    if (!string.IsNullOrEmpty(sql))
                    {
                        DataSet dataSet = ExcuteSqlDataSet(sql);
                        if (dataSet != null && dataSet.Tables[0].Rows.Count == 1)
                        {
                            int temp = Convert.ToInt32(dataSet.Tables[0].Rows[0]["id"]);
                            if (temp > 0)
                            {
                                result.ResultNumber = ResultEnum.Success;
                                result.Obj = temp;
                            }
                            else
                            {
                                result.ResultNumber = ResultEnum.Error;
                                result.Describe = "更新数据失败";
                            }
                        }
                    }
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Describe = "请输入有效数据";
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }

        /// <summary>
        ///     删除停车柱
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultInfo<bool> DeleteLockPile(int id)
        {
            var result = new ResultInfo<bool>();
            try
            {
                string sql = string.Format("delete from jsh_lockpile where id={0}", id);
                int temp = ExcuteSql(sql);
                if (temp > 0)
                {
                    result.ResultNumber = ResultEnum.Success;
                    result.Obj = true;
                }
                else
                {
                    result.ResultNumber = ResultEnum.Error;
                    result.Obj = false;
                }
            }
            catch (Exception)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = "删除失败";
            }
            return result;
        }

        private static List<LockPileView> PopulateLockPiles(IEnumerable<jsh_lockpile> piles)
        {
            int i = 0;
            var lockPiles = new List<LockPileView>();
            foreach (jsh_lockpile pile in piles)
            {
                i++;
                lockPiles.Add(new LockPileView
                {
                    Serial = i,
                    LockNo = pile.Pileno,
                    Status = pile.Status,
                    ControlBoxNo = pile.Controlbox,
                    Ip = pile.Ip,
                    Block = pile.Area,
                    ID = pile.id
                });
            }
            return lockPiles;
        }
    }
}